package com.sky.service.admin.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.admin.ReportService;
import com.sky.vo.TurnoverReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("adminReportServiceImpl")
@Slf4j
public class ReportServiceImpl implements ReportService {

    private final OrderMapper orderMapper;


    public ReportServiceImpl(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    /**
     * 统计指定时间内的营业额数据
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return TurnoverReportVO
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        log.info("执行 统计指定时间内的营业额数据 业务: {},{}",begin,end);
        //存放从begin到end中间的时间集合
        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        //存放每天的营业额
        List<Double> turnovers = new ArrayList<>();

        for (LocalDate date : dates) {
            //查询date 日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Map<String,Object> timeMap = new HashMap<>();
            timeMap.put("begin",beginTime);
            timeMap.put("end",endTime);
            timeMap.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getSumByTimeMap(timeMap);
            if (turnover==null){
                turnover = 0.0;
            }
            turnovers.add(turnover);

        }

        //封装返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .turnoverList(StringUtils.join(turnovers,","))
                .build();
    }
}
